package pl.ciaastek.ubuntucontrol;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSchException;

class Exec extends AsyncTask<String, String, String> {

	private Context context;
	ProgressDialog dialog;
	String com;
	Connection connection;

	public Exec(Context cxt, Connection conn) {

		connection = conn;
		context = cxt;
		dialog = new ProgressDialog(context);
	}

	@Override
	protected void onPreExecute() {
		dialog.setCancelable(false);
		dialog.show();
	}

	protected void onProgressUpdate(String... progress) {
		String tmpStr = (String) progress[0];
		dialog.setMessage(tmpStr);
	}

	protected void onPostExecute(String result) {
		if (dialog.isShowing()) {
			dialog.dismiss();
		}
		return;
	}

	@Override
	protected String doInBackground(String... some) {
		String result = null;
		publishProgress(some[4]);
		try {
			connection.channelExec = connection.session.openChannel("exec");
			connection.fromServerExec = new BufferedReader(
					new InputStreamReader(
							connection.channelExec.getInputStream()));
			((ChannelExec) connection.channelExec).setCommand(some[4]);
			connection.channelExec.connect();

		} catch (JSchException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		result += "n\n";
		result += "All steps executed!";
		return result;
	}

}
